package dao

import (
	"mldong/internal/modules/sys/entity"
	"mldong/utility"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
)

type DictDao struct {
}

func (u *DictDao) Insert(entity entity.Dict, tx gdb.TX) (res entity.Dict, _ error) {
	var now = gtime.Now()
	entity.CreateTime = now
	entity.UpdateTime = now
	if entity.ID == nil {
		entity.ID = utility.GenId()
	}
	var _, err = u.Model(tx).Data(entity).Insert()
	return entity, err
}

func (u *DictDao) UpdateById(entity entity.Dict, tx gdb.TX) (count int64, _ error) {
	var now = gtime.Now()
	entity.UpdateTime = now
	var result, err = u.Model(tx).Data(entity).Where("id=?", entity.ID).Update()
	count, _ = result.RowsAffected()
	return count, err
}

func (u *DictDao) DeleteById(id string, tx gdb.TX) (count int64, _ error) {
	var now = gtime.Now()
	var result, err = u.Model(tx).Data(g.Map{"is_deleted": 1, "update_time": now}).Where("id=?", id).Update()
	if err != nil {
		return 0, err
	}
	count, _ = result.RowsAffected()
	return count, nil
}

func (u *DictDao) DeleteByIds(ids []string) (count int64, _ error) {
	var now = gtime.Now()
	var result, err = g.Model("sys_dict").Data(g.Map{"is_deleted": 1, "update_time": now}).WhereIn("id", ids).Update()
	if err != nil {
		return 0, err
	}
	count, _ = result.RowsAffected()
	return count, nil
}

func (u *DictDao) GetById(id string) (res entity.Dict, err error) {
	var model = g.Model("sys_dict").Where("id=?", id)
	model = model.Where("is_deleted=?", 0)
	err = model.Scan(&res)
	return res, err
}

func (u *DictDao) Page(pageNum int, pageSize int, modelHandler func(m *gdb.Model) *gdb.Model) (users []entity.Dict, total int, err error) {
	var model = g.Model("sys_dict t")
	// 允许外部修改 model
	if modelHandler != nil {
		model = modelHandler(model)
	}
	model = model.Where("t.is_deleted=?", 0)
	err = model.Page(pageNum, pageSize).ScanAndCount(&users, &total, false)
	return users, total, err
}

func (u *DictDao) List(modelHandler func(m *gdb.Model) *gdb.Model) (list []entity.Dict, err error) {
	var model = g.Model("sys_dict")
	// 允许外部修改 model
	if modelHandler != nil {
		model = modelHandler(model)
	}
	model = model.Where("is_deleted=?", 0)
	err = model.Scan(&list)
	return list, err
}

func (u *DictDao) Model(tx gdb.TX) *gdb.Model {
	if tx != nil {
		return tx.Model("sys_dict")
	}
	return g.Model("sys_dict")
}

func NewDictDao() *DictDao {
	return &DictDao{}
}
